package com.siao.util;

import java.security.MessageDigest;

/**
 * @author SiaoLeon
 * MD5处理工具
 */
public class MD5 {

	/**
	 * 转为MD5码
	 * @param source 原字节数组
	 * @return MD5字符串
	 */
	public static String encrypt(byte[] source) {
		String string = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);

			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];
			int k = 0;

			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}

			string = new String(str);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return string;
	}

	/**
	 * 转为MD5码
	 * @param source 原文本
	 * @return MD5字符串
	 */
	public static String encrypt(String source) {
		return encrypt(source.getBytes());
	}

}
